package xx.iverson.school_manage.controller;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.ss.usermodel.*;
import xx.iverson.school_manage.userutil.UserInsertion;

/**
 * xx.iverson.school_manage.controller.DownloadController
 * <p>
 * on 2024/9/14
 *
 * @author weijx
 */
@RestController
@RequestMapping
public class DownloadController {
    private final ResourceLoader resourceLoader;

    public DownloadController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @GetMapping("/downloadTemplate")
    public ResponseEntity<Resource> downloadImportTemplate() throws IOException {
        Resource resource = resourceLoader.getResource("classpath:/static/template/导入名单模板-（只适用于导入老师）.xlsx");

        if (!resource.exists()) {
            throw new RuntimeException("文件不存在：" + resource.getFilename());
        }

        String encodedFileName = URLEncoder.encode(resource.getFilename(), StandardCharsets.UTF_8.name());
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + encodedFileName)
                .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                .body(new UrlResource(resource.getURI()));
    }

    @PostMapping("/upload")
    public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (!file.getOriginalFilename().endsWith(".xlsx")) {
            return ResponseEntity.badRequest().body("Only .xlsx files are allowed!");
        }

        try (InputStream is = file.getInputStream()) {
            Workbook workbook = new XSSFWorkbook(is);
            Sheet sheet = workbook.getSheetAt(0); // 假设只处理第一个工作表
            List<List<String>> data = new ArrayList<>();

            int startRow = 3; // 从第三行开始
            List<String> names = new ArrayList<>();
            List<String> phones = new ArrayList<>();
            List<Integer> classes = new ArrayList<>();
            for (int rowIndex = startRow; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
                Row row = sheet.getRow(rowIndex);
                if (row == null) continue;
                phones.add(getStringCellValue(row.getCell(0))); // phone
                names.add(getStringCellValue(row.getCell(1))); // realname
                classes.add(Integer.valueOf(getStringCellValue(row.getCell(2)))); // classes
            }

            // 这里可以将数据保存到数据库或其他地方
            UserInsertion.importData(names, phones, classes);
            return ResponseEntity.ok().body("File uploaded successfully!");
        } catch (IOException e) {
            return ResponseEntity.status(500).body("Error processing file");
        }
    }

    private String getStringCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }

        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                return cell.getStringCellValue();
            case Cell.CELL_TYPE_NUMERIC:
                // 检查是否是日期格式
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    // 将数字转换为字符串，去除小数部分
                    return String.format("%.0f", cell.getNumericCellValue());
                }
            default:
                return "";
        }
    }
}
